package com.dispatcher.receiver;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;

import com.alibaba.fastjson.JSON;
import com.dispatcher.HomeTabActivity;
import com.dispatcher.R;
import com.dispatcher.bean.PushData;

public class MyPushReceiver extends BroadcastReceiver {
	private static final String TAG = "MyPushReceiver";
	private NotificationManager nManager;
	private byte[] lock = new byte[1];
	private Context mContext;
	
    PushData pushData = null;
//    int oldnid = 0;
    List<Integer> oldnid;
	
	private SharedPreferences sharedPrefs;
	private SharedPreferences spf;
	@Override
	public void onReceive(Context context, Intent intent) {
		
		mContext = context;
		Bundle bundle = intent.getExtras();
		Log.d(TAG, "onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
		
		nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		
		
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "接收Registration Id : " + regId);
            //send the Registration Id to your server...
        }else if (JPushInterface.ACTION_UNREGISTER.equals(intent.getAction())){
        	String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "接收UnRegistration Id : " + regId);
            //send the UnRegistration Id to your server...
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
        	Log.d(TAG, "接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
        	
        	String msgExtra = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            
            pushData = JSON.parseObject(msgExtra, PushData.class);
            
            handleNotification(pushData);
            
//            String ntype = null;
//            String listid = null;
//            if(pushData != null) {
//            	ntype = pushData.getNtype();
//            	listid = pushData.getListid();
//            }
//            
//            if(ntype != null && listid != null) {
//            }
            
//			if(isTopActivity()) {
//				// 获取当前社区id
//				String cid=sharedPrefs.getString(Commstr.SHAREPRE_CurCID, "");
//				if(!cid.equals(listid)) {	// 其他社区有推送信息
//					synchronized (lock) {
//		            	notifyCtrl.insert(pushData);
//		            }
//					
//					handleNotification(pushData);
//					
//				} else {
//					handleMsg(pushData);
//					
//				}
//			} else {
//				
//				if(oldnid.size() != 0 && oldnid.get(0) != 0) {
//					nManager.cancel(oldnid.get(0));
//				}
//				
//				synchronized (lock) {
//	            	notifyCtrl.insert(pushData);
//	            }
//				handleNotification(pushData);
//			}
//			
//			g_dbctrl.releaseSource();
        
        } 
	}

	// 打印所有的 intent extra 数据
	private static String printBundle(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			} else {
				sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
			}
		}
		return sb.toString();
	}
	
	// 程序启动时，处理推送消息，通知相关页面从服务器拉数据
//	private void handleMsg(PushData pushData) {
//		MsgCenter msgCenter=MsgCenter.getInstance();
//		// 将消息发送到消息中心
//		MsgData d = msgCenter.getMsgInstance();
//		String ntype = pushData.getNtype();
//		if(ntype != null) {
//			Intent i = new Intent();
//			i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//			i.setClass(mContext, HomeTabActivity.class);
//			i.putExtra("action", "request_unread");
//			mContext.startActivity(i);
//		}
//		msgCenter.postMsg(d);
//		
//	}
	
	// 程序未启动时，处理推送通知
	private void handleNotification(PushData pushData) {
		
		
     	Notification notify = new Notification();
     	notify.flags = Notification.FLAG_AUTO_CANCEL;
     	notify.icon = R.drawable.ic_launcher;
     	notify.defaults  = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
		
		
		PendingIntent contentIntent = null;
				Intent i = new Intent();
				
		        contentIntent = PendingIntent.getActivity(mContext, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
				notify.tickerText = "有新订单了";
		     	notify.setLatestEventInfo(mContext, "有新订单了", pushData.getDisplaymsg(), contentIntent);
		
		     	
		if(pushData.getMsgtype()==null){
			nManager.notify(0, notify);
		}
		else if(pushData.getMsgtype().equals("newOrder")){
			nManager.notify(0, notify);
		}else if(pushData.getMsgtype().equals("newWxmsg")){
			nManager.notify(1, notify);
		}
	}
	
	// 判断程序是否在前台运行
	private boolean isTopActivity() {
        String packageName = "com.zuzhili";
        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo>  tasksInfo = activityManager.getRunningTasks(1);  
        
        if(tasksInfo.size() > 0){  
            // 应用程序位于堆栈的顶层  
            if(packageName.equals(tasksInfo.get(0).topActivity.getPackageName())){  
                return true;  
            }  
        }  
        return false;
    }
	
	// 判断程序是否在后台运行
	private boolean isRunningInBackground() {
		String packageName = "com.zuzhili";
		
		ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo>  tasksInfo = activityManager.getRunningTasks(20); 
        int taskNum = tasksInfo.size();
        int i = 0;
		while(taskNum > 0) {
			if(packageName.equals(tasksInfo.get(i++).topActivity.getPackageName())){  
                return true;  
            }
			taskNum--;
		}
		return false;
	}
}
